from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
# 输入输出以及关键参数
continuous_map_name = "picture/grayscale.png"

# 打开原始二值图像并转换为灰度图像
img = Image.open(continuous_map_name).convert('L')

# 生成图像矩阵, 取值0-255，灰度图像，大小取决于png图片分辨率
map_grid = np.array(img)

# 使用阈值30进行二值化
threshold = 30
map_grid = np.where(map_grid > threshold, 1, 0)


# 输入原始图像矩阵、期望大小，对其进行大小调整，输出二值矩阵
def map_resize(grid, height, width):
    resized_map = np.zeros((height, width))
    rate_height = grid.shape[0]/height
    rate_width = grid.shape[1]/width
    for i in range(0, height):
        for j in range(0, width):
            have_barrier = False    # 用于判断是否有障碍物, False 表示无障碍
            h_start, h_end = round(i*rate_height), round((i+1)*rate_height)
            w_start, w_end = round(j*rate_width), round((j+1)*rate_width)
            for h in range(h_start, h_end):
                for w in range(w_start, w_end):
                    if grid[h][w] == 0:     # 0是黑色，表示障碍物
                        have_barrier = True
                        break
                if have_barrier:
                    break
            if not have_barrier:
                resized_map[i][j] = 255     # 255是白色，表示无障碍物,也可以用其他数字

    resized_map = resized_map.astype(np.uint8)
    # np.save('npy/resized_map_400.npy', resized_map)
    return resized_map


def test1():
    # 生成新的二值矩阵
    new_map = map_resize(map_grid, 400, 400)

    # 保存新的二值图像
    new_img = Image.fromarray(new_map)
    new_img.save("picture/binary_resized_400.png")

    # 显示新的二值图像
    plt.imshow(new_map, cmap='gray')
    plt.grid(True)
    plt.show()


def test2():
    # 打开原始二值图像并转换为灰度图像
    img = Image.open('picture/grayscale.png').convert('L')

    # 生成图像矩阵, 取值0-255，灰度图像，大小取决于png图片分辨率
    map_grid = np.array(img)
    new_map = map_resize(map_grid, 600, 600)
    np.save('npy/resized_map_600_600.npy', new_map)
    plt.imshow(new_map, cmap='gray')
    plt.show()

    print(new_map.shape)


if __name__ == '__main__':
    # test1()
    test2()
